<template>
  <BreadCrumb>
    <template #default>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'DyjCourseList' }">课程列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{ textMap[props.type] }}课程</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
  </BreadCrumb>
  <PageListContainer class="base-block notice-list">
    <k-form ref="formRef" :model="state.model" :rules="rules" label-width="90px">
      <el-form-item label="课程名称" prop="title">
        <el-input
          v-model="state.model.title"
          :disabled="props.type === 'check'"
          clearable
          placeholder="请填写课程标题"
          style="width: 60%"
          maxlength="14"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="课程类型" prop="classify">
        <el-select v-model="state.model.classify" placeholder="请选择课程类型" style="width: 320px">
          <template v-for="item in classifyOptions" :key="item.value">
            <el-option v-if="item.value > 0" :label="item.label" :value="item.value" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="成长阶段" prop="stage">
        <el-select v-model="state.model.stage" placeholder="请选择发送对象" style="width: 320px">
          <template v-for="item in stageOptions" :key="item.value">
            <el-option v-if="item.value > 0" :label="item.label" :value="item.value" />
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="视频链接" prop="course_url">
        <el-input v-model="state.model.course_url" :disabled="props.type === 'check'" clearable placeholder="请输入视频链接" style="width: 380px" />
        <el-button :disabled="analLoading" type="primary" class="anal-button" @click="handleAnal">解析</el-button>
      </el-form-item>
      <div v-if="analList?.length" v-loading="analLoading" class="anal-box">
        <div class="mb-10">解析视频</div>
        {{ ananList }}
        <div v-for="(item, index) in analList" :key="index" class="anal-card">
          <div class="cover-box">
            <img :src="item.cover" class="cover" alt="" />
          </div>

          <div class="content">
            <el-tooltip :content="item.title" :disabled="!item.title?.length" placement="top">
              <div class="flex-box title-box">
                <div class="icon mr-5" :class="{photo: item.photo}"></div>
                <div class="title" :class="{ 'has_fusion': item.has_fusion_goods }" @click="handleJumpUrl(item.play_url)">{{ item.title }}</div>
              </div>
            </el-tooltip>
            <div class="user-info">
              <div class="user">
                <div class="avatar-box mr-5">
                  <img class="avatar" :src="item.user_url" alt="" />
                </div>

                <EllipsisText :content="item.nick_name" :width="item.has_fusion_goods ? 100 : 250" show-tooltip />
              </div>
              <div v-if="item.has_fusion_goods" class="goods">
                <div class="icon"></div>
                <EllipsisText :content="item.goods_title" :width="150" show-tooltip />
              </div>
            </div>
            <div class="date">{{ dayjs.unix(item.create_time).format('YYYY-MM-DD HH:MM:ss') }}</div>
          </div>
          <div class="clear-btn" @click="handleRemove">
            <el-icon class="btn"><CircleCloseFilled /></el-icon>
          </div>
        </div>
      </div>
      <div v-else class="anal-box empty"></div>
      <el-form-item label-width="40%">
        <el-button :disabled="state.loading" @click="goBackList">返回</el-button>
        <el-button :loading="state.loading" type="primary" @click="methods.onSubmit">保存</el-button>
      </el-form-item>
    </k-form>
  </PageListContainer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { ref, computed, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useForm } from '@crud/index';

import { classifyOptions, stageOptions } from '@/views/crm-dyj/course/course-list/hooks/use-table';
import { add, edit, getAnalResult, getDetail } from '@/api/crm-dyj/course';

import BreadCrumb from '@/components/base-bread-crumb/index.vue';
import EllipsisText from '@/components/base-ellipsis-text/index.vue';

defineOptions({ name: 'DyjCourseAdd' });
const route = useRoute();
const router = useRouter();
const props = route.query as Record<string, any>;
const isEdit = computed(() => props.type === 'edit');
const analLoading = ref(false);

const analList = ref([]);
// 返回
const goBackList = () => {
  router.push({ name: 'DyjCourseList' });
};

const textMap = {
  create: '新增',
  edit: '编辑',
  check: '查看'
};
const formRef = ref();

const rules = {
  title: [{ required: true, message: '请填写消息标题' }],
  classify: [{ required: true, message: '请选择课程类型' }],
  stage: [{ required: true, message: '请选择发送对象' }],
  course_url: [{ required: true, message: '请输入视频链接' }]
};
const { state, ...methods } = useForm({
  formRef,
  model: {
    title: '',
    classify: 1,
    stage: 1,
    course_url: ''
  },
  onSubmit: async (model: any, mode = 0) => {
    let validate = false;
    if (formRef?.value?.validate) {
      validate = await formRef.value.validate();
    }
    if (!validate) return;
    state.loading = true;
    if (props.type === 'create') {
      const res = await add(model).finally(() => (state.loading = false));
      if (res.err) return;
      ElMessage.success('发布成功');
      router.push({ name: 'DyjCourseList' });
    } else if (isEdit.value) {
      if (!props.id) return;
      const res = await edit({ ...model, id: props.id }).finally(() => (state.loading = false));
      if (res.err) return;
      ElMessage.success('编辑成功');
      router.push({ name: 'DyjCourseList' });
    }
  }
});

// 获取详情
const getDetailInfo = async () => {
  const res = await getDetail({ id: props.id });
  const { data, err } = res;
  if (err) return;
  if (data) {
    state.model = {
      ...state.model,
      ...data,
      publish_time: data.publish_time
    };
    /** 获取详情后，再获取解析视频的详细信息 */
    nextTick(() => handleAnal());
  } else {
    state.model = {
      classify: 1,
      stage: 1
    };
    ElMessage.error('找不到该课程');
  }
};
// 编辑
if (isEdit.value || props.type === 'check') {
  getDetailInfo();
}
/** 解析视频链接 */
const handleAnal = async () => {
  const { course_url } = state.model;
  await formRef.value?.validateField(['course_url']);

  analLoading.value = true;
  const res = await getAnalResult({ course_url }).finally(() => (analLoading.value = false));
  console.log(res);
  if (!res.err) {
    analList.value = [].concat(res.data);
  } else {
    analList.value = [];
  }
};

/** 跳转到视频链接 */
const handleJumpUrl = (url: string) => {
  window.open(url, '_blank');
};
/** 移除解析视频 */
const handleRemove = () => {
  analList.value = [];
};
</script>
<style lang="scss" scoped>
.anal-button {
  border-radius: 0;
}

.flex-box {
  display: flex;

  &.title-box {
    margin-bottom: 3px;

    .icon {
      width: 16px;
      height: 16px;
      background-image: url('@/assets/images/icons/svg/dyj-icon-video.svg');
      background-size: 100% 100%;

      &.photo {
        background-image: url('@/assets/images/icons/svg/dyj-icon-photo.svg');
      }
    }
  }
}

.notice-content {
  width: 80%;
  min-height: 300px;
  padding: 20px;
  word-break: break-all;
  white-space: pre-wrap;
  border: solid 1px #ccc;
}

.anal-box {
  box-sizing: border-box;
  width: 100%;
  padding: 16px;
  padding-top: 10px;

  // height: 300px;
  margin-bottom: 200px;
  background-color: #f1f1f1;

  &.empty {
    height: 300px;
    margin-bottom: 0;
    background-color: #fff;
  }

  .anal-card {
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    width: 446px;
    height: 90px;
    padding: 12px;
    background-color: #fff;

    .cover {
      width: 66px;
      height: 66px;
      border-radius: 4px;
    }

    .content {
      padding: 4px 0;
      padding-left: 4px;
      font-size: 14px;
      line-height: 18px;
      color: #4e5969;

      .title {
        width: 320px;
        margin-bottom: 4px;
        overflow: hidden;
        font-weight: 500;
        color: #1d2129;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;

        &.has_fusion {
          color: #ED675A;
        }
      }

      .user-info {
        display: flex;
        justify-content: space-between;

        .user {
          display: flex;
        }

        .avatar-box {
          display: inline-block;

          .avatar {
            width: 16px;
            height: 16px;
            border-radius: 50%;
          }
        }

        .name {
          margin-left: 5px;
        }

        .goods {
          display: flex;
          align-items: center;
          padding: 2px;
          color: #86909c;
          background: #f7f8fa;
          border-radius: 2px;

          .icon {
            width: 14px;
            height: 14px;
            color: #ffe298;
            background-image: url('@/assets/images/icons/svg/dyj-cart.svg');
          }
        }
      }
    }

    .clear-btn {
      display: flex;
      align-items: center;

      .btn {
        color: #ddd;
        cursor: pointer;
        transition: color .3s ease;

        &:hover {
          color: red;
        }
      }
    }
  }
}
</style>
